<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <Actions @save="saveUser" :user="user" class="actions-container" />

      <BasicForm ref="basicFormRef" :user="user" />

      <a-divider :user="user" />

      <PositionForm ref="positionFormRef" :user="user" />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { getUser, userAdd } from '@/api/flow/user'
import Actions from './Actions.vue'
import BasicForm from '../modify/Basic.vue'
import PositionForm from '../modify/Position.vue'
// userAdd
export default {
  data () {
    return {
      getUserAsync: null,
      user: {
        department_identity: '',
        mobile: '',
        femail: '',
        username: '',
        role: [],
        group: [],
        position: [],
      },

      state: {
        loading: false,
      },
    }
  },

  components: {
    Actions,
    BasicForm,
    PositionForm,
  },

  methods: {
    // form
    validateFieldsForm () {
      const basicForm = this.$refs.basicFormRef.form
      const positionForm = this.$refs.positionFormRef.form

      return new Promise((resolve, reject) => {
        basicForm.validateFieldsAndScroll((err, values) => {
          if (!err) {
            positionForm.validateFieldsAndScroll((err, values) => {
               if (!err) {
                 resolve(values)
                 return values
               }
              reject(values)
            })
          } else {
            reject(values)
          }
        })
      })
    },

    // 提交表单
    submitForm () {
      return new Promise((resolve, reject) => {
        const basicForm = this.$refs.basicFormRef.form
        const positionForm = this.$refs.positionFormRef.form

        const data = {
          ...basicForm.getFieldsValue(),
          ...positionForm.getFieldsValue(),
        }

        userAdd(data)
          .then((data) => {
            this.$notification.success({
              message: '添加人员成功, 请保存密码!',
              description: data.reset_password.toString(),
            })

            resolve(data)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 保存用户
    saveUser () {
      const { state } = this

      this.validateFieldsForm()
        .then(() => {
          this.submitForm()
            .then((res) => {
               this.$router.go(-1)
            })
            .finally(() => {
              state.loading = false
            })
        })
        .catch(() => {
          state.loading = false
        })
    },
  },
}

</script>

<style lang="scss" scoped>
.actions-container {
  margin-bottom: $margin-md;
}
</style>
